<?php
class CodeSpace_Oauth_Server_Request_Transmission extends CodeSpace_Oauth_Server_Request_Abstract
{
    public function __construct ($options = null)
    {
        if (! is_null($options))
        {
            if (array_key_exists('oauth_token', $options))
            {
                $this->_token = new Zend_Oauth_Token_AuthorizedRequest();
                $this->_token->setToken($options['oauth_token']);
                
                $tokenTable = new Model_DbTable_Tokens();
                $resultSet = $tokenTable->find($options['oauth_token']);
                  
                if($resultSet->count() == 0 || $resultSet->count() > 1)
                {
                    throw new Exception('Invalid Access Token : ' . $options['oauth_token']);
                }
                
                $token = $resultSet->current();
                $this->_token->setTokenSecret($token->tkn_token_secret);
                unset($options['oauth_token']);
            }
        }
        parent::__construct($options);
    }
    
    public function checkSignature()
    {
        return true;
    }
    
    public function process(CodeSpace_Oauth_Server $server)
    {
        $userParams = $server->getConfig()->getUserParams();
        
        $serviceIdentity = $userParams['service_identity'];
        $serviceType = $userParams['service_type'];
        
        unset($userParams['service_identity']);
        unset($userParams['service_type']);
        
        $serviceTable = new Model_DbTable_Services();
        $service = $serviceTable->find($serviceIdentity)->current();
        $serviceAddress = $service->srv_address;
        
        $client = new Zend_Rest_Client($serviceAddress);
        $userParams = $server->signRequest($userParams);
        
        $t = $server->getConfig()->getToken()->getToken();
        $owners = new Model_DbTable_ResourceOwners();
        $rowSet = $owners->find($t);
        if($rowSet->count() == 1)
        {
            $row = $rowSet->current();
            $userParams['owner'] = $row->rown_identification; 
        }
        
        echo $_SERVER['REQUEST_METHOD']; exit;
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                $result = $client->restGet($_SERVER['REDIRECT_URL'], $userParams);
            break;
            case 'POST':
                break;
            case 'PUT':
                break;
            default:
                throw new Exception('Invalid Request Type');
                break;
        }
        
        // Send back the response to the consumer
        $front = Zend_Controller_Front::getInstance();
        $front  ->getResponse()
                ->setHttpResponseCode($result->getStatus())
                ->appendBody($result->getBody())
                ->sendResponse();
        exit;
    }
}
?>